package com.zangs.emqx_expand.system.service.impl;

import com.zangs.emqx_expand.common.core.domain.TreeNode;
import com.zangs.emqx_expand.system.domain.Api;
import com.zangs.emqx_expand.system.mapper.ApiMapper;
import com.zangs.emqx_expand.system.service.IApiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * apiService业务层处理
 *
 *
 * @since 2025-01-16
 */
@Service
public class ApiServiceImpl implements IApiService {
    @Autowired
    private ApiMapper apiMapper;

    /**
     * 查询api
     *
     * @param id api主键
     * @return api
     */
    @Override
    public Api selectApiById(String id) {
        return apiMapper.selectApiById(id);
    }

    /**
     * 查询api列表
     *
     * @param api api
     * @return api
     */
    @Override
    public List<Api> selectApiList(Api api) {
        return apiMapper.selectApiList(api);
    }

    /**
     * 新增api
     *
     * @param api api
     * @return 结果
     */
    @Override
    public int insertApi(Api api) {
        return apiMapper.insertApi(api);
    }

    /**
     * 修改api
     *
     * @param api api
     * @return 结果
     */
    @Override
    public int updateApi(Api api) {
        return apiMapper.updateApi(api);
    }

    /**
     * 批量删除api
     *
     * @param ids 需要删除的api主键
     * @return 结果
     */
    @Override
    public int deleteApiByIds(String[] ids) {
        return apiMapper.deleteApiByIds(ids);
    }

    /**
     * 删除api信息
     *
     * @param id api主键
     * @return 结果
     */
    @Override
    public int deleteApiById(String id) {
        return apiMapper.deleteApiById(id);
    }

    @Override
    public int deleteApiAll() {
        return apiMapper.deleteApiAll();
    }

    @Override
    public List<Api> selectAppUserByAppUserId(Long appUserId) {
        return apiMapper.selectAppUserByAppUserId(appUserId);
    }

    @Override
    public List<TreeNode> selectAuthApi(Long appUserId) {
        List<Map<String, Object>> maps = apiMapper.selectAuthApi(appUserId);

        if (!CollectionUtils.isEmpty(maps)) {

            TreeNode treeNode = buildTree(maps);
            return new ArrayList<>(treeNode.getChildren());
        }

        return Collections.emptyList();
    }


    public static TreeNode buildTree(List<Map<String, Object>> dataList) {
        TreeNode rootNode = new TreeNode("root");
        Map<String, TreeNode> nodeMap = new HashMap<>();
        nodeMap.put("", rootNode);

        for (Map<String, Object> data : dataList) {
            String[] parts = data.get("methodName").toString().split("\\.");
            for (int i = 0; i < parts.length; i++) {
                String part = parts[i];
                String keyPath = buildKeyPath(parts, i + 1);
                TreeNode childNode = nodeMap.get(keyPath);
                if (childNode == null) {
                    childNode = new TreeNode(part);
                    TreeNode parentNode = nodeMap.get(buildKeyPath(parts, i));
                    parentNode.getChildren().add(childNode);
                    nodeMap.put(keyPath, childNode);
                }
                if (i == parts.length - 1) {
                    //处理叶子节点
                    childNode.setId(data.get("id").toString());
                    childNode.setChecked((long)data.get("checked")>0);
                    childNode.setLabel(childNode.getLabel() + " " + data.get("url") + " " + data.get("requestMethod") + ((Boolean) data.get("signature") ? " [需要验签] " : " [无需验签] ") + " " + data.get("remark"));
                }
            }

        }


        return rootNode;
    }

    private static String buildKeyPath(String[] parts, int end) {
        StringBuilder key = new StringBuilder();
        for (int i = 0; i < end; i++) {
            if (i > 0) {
                key.append(".");
            }
            key.append(parts[i]);
        }
        return key.toString();
    }


    public static void printTree(TreeNode node, int level) {
        if (node == null) {
            return;
        }

        for (int i = 0; i < level; i++) {
            System.out.print("  "); // 打印缩进
        }

        System.out.println(node.getLabel());
        for (TreeNode child : node.getChildren()) {
            printTree(child, level + 1);
        }
    }

}
